package com.example.dllo.moondog.information.newsss.loadpicture;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dllo.moondog.R;

import org.json.JSONArray;

import java.util.List;

/**
 * Created by dllo on 16/1/15.
 */
public class AdvertisementAdapter extends PagerAdapter {
    private Context context;
    private List<View> views;
    JSONArray advertiseArray;

    public AdvertisementAdapter(Context context, List<View> views, JSONArray advertiseArray) {
        this.context = context;
        this.views = views;
        this.advertiseArray = advertiseArray;
    }

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager)container).removeView(views.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ((ViewPager)container).addView(views.get(position),0);
        final int POSITION = position;
        View view = views.get(position);
        try {
            String head_img = advertiseArray.optJSONObject(position).optString("head_img");
            ImageView ivAdvertise = (ImageView) view.findViewById(R.id.ivAdvertise);
            // 加载网络图片
            ImageLoaderUtil.getImage(context, ivAdvertise, head_img, R.mipmap.holder, R.mipmap.holder, 380, 300);
            // item的点击监听
            ivAdvertise.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("ShowToast")
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "第" + POSITION + "个广告图片被点击", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }
}
